package com.aspirecn.core.datacache;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.configuration.XMLConfiguration;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.aspirecn.core.commons.Configuration;

public class ShareCommonCache extends BaseLocalCache {

	public final static Logger logger = Logger
			.getLogger(ShareCommonCache.class);

	private Map<String, String> paramMap = new HashMap<String, String>();

	private static ShareCommonCache instance = new ShareCommonCache();

	private ShareCommonCache() {

		this.dataFile = new File(Configuration.getInstance()
				.getDownloadFilePath() + File.separator + "sharecommon.xml");
		load();
	}

	public static ShareCommonCache getInstance() {
		return instance;
	}

	@Override
	public void load() {
		if (!loading.getAndSet(true)  && this.dataFile.exists()) {

			//内容少，无需清空
			//clear();

			try {
				XMLConfiguration config = new XMLConfiguration(this.dataFile);

				int maxno = config.getMaxIndex("parameter");

				for (int i = 0; i <= maxno; i++) {

					String name = config.getString("parameter(" + i + ").name");
					String value = config.getString("parameter(" + i
							+ ").value");

					paramMap.put(StringUtils.trimToEmpty(name), StringUtils.trimToEmpty(value));

				}

				updateFileDownloadTime();

				logger.info("ShareCommon配置信息加载完成");

			} catch (Exception e) {
				logger.error("ShareCommon配置信息出现异常", e);
			}

		}

		loading.set(false);
	}

	public void clear() {		
		
		paramMap.clear();
	}
	
	public String get( String key )
	{
		return this.paramMap.get(key);
	}

	public void reload() {
		if (this.fileIsChange()) {
			this.load();
		} else {
			logger.info("没变化，sharecommon.xml信息未加载");
		}
	}
}
